import { defineStore } from "pinia";
import { reactive } from "vue";
import {apiSysAuthUserInfoGet,apiSysConstListGet,apiSysDictTypeAllDictListGet} from '@/api/sys/sysAuth'
import { Local,Session } from "@/utils";
import type { ResType } from "@/api/types";
import { useThemeConfig } from "./themeConfig";

export const useUserInfo = defineStore("userInfo", ()=>{
    const state = reactive({
        userInfos:{} as any,
        constList:[]as any,
        dictList:{}as any
    })
    // 存储用户信息到浏览器缓存
    const setUserInfos = async ()=>{
        state.userInfos =  await getApiUserInfo()
    }
    // 存储常量信息到浏览器缓存
    const setConstList = async ()=>{
        state.constList =  await getSysConstList()
    }
    // 存储字典信息到浏览器缓存
    const setDictList = async()=>{
        state.dictList = await getSysDictList()
    }

    // 获取当前用户信息
    const getApiUserInfo = async ()=>{
        const res = await apiSysAuthUserInfoGet() as ResType<any>
        let d = res.data.result
        d.buttons = d.buttons.filter((i:any)=>!!i)
        const userInfos = {
            id: d.id,
            account: d.account,
            realName: d.realName,
            phone: d.phone,
            idCardNum: d.idCardNum,
            email: d.email,
            accountType: d.accountType,
            avatar: d.avatar ?? '/upload/logo.png',
            address: d.address,
            signature: d.signature,
            orgId: d.orgId,
            orgName: d.orgName,
            posName: d.posName,
            roles: d.roleIds,
            authBtnList: d.buttons,
            tenantId: d.tenantId,
            time: new Date().getTime(),
        };
        const themeConfig = useThemeConfig()
        themeConfig.themeConfig.watermarkText = d.watermarkText ?? '';
        Local.remove('themeConfig') //移除旧的配置信息
        Local.set('themeConfig',themeConfig.themeConfig) //存储新的配置信息
        return userInfos
    }

    // 获取常量集合
    const getSysConstList = async ()=>{
        const res = await apiSysConstListGet() as ResType<any>
        return res.data.result ?? []
    }
    
    const getSysDictList = async ()=>{
        const res = await apiSysDictTypeAllDictListGet() as ResType<any>
        return res.data.result ?? {}
    }

    return {
        state,
        setUserInfos,
        setConstList,
        setDictList
    }
})